package logic

import (
	"context"
	"go-zero-project-02/rpc_study/user_api_rpc/models"
	"time"

	"go-zero-project-02/rpc_study/user_api_rpc/rpc/internal/svc"
	"go-zero-project-02/rpc_study/user_api_rpc/rpc/types/user"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserCreateLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserCreateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserCreateLogic {
	return &UserCreateLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UserCreateLogic) UserCreate(in *user.UserCreateRequest) (*user.UserCreateResponse, error) {
	var model models.UserModel
	err := l.svcCtx.MysqlDb.Take(&model, "username = ?", in.Username).Error
	if err != nil {
		model = models.UserModel{
			Username:      in.Username,
			Password:      in.Password,
			RegisterTime:  time.Now(),
			LastLoginTime: time.Now(),
		}
		err := l.svcCtx.MysqlDb.Create(&model).Error
		if err != nil {
			logx.Error("创建失败")
			return &user.UserCreateResponse{
				Err: "创建失败",
			}, nil
		}
		return &user.UserCreateResponse{
			Err:    "创建成功",
			UserId: uint32(model.Id),
		}, nil

	}
	return &user.UserCreateResponse{
		Err: "记录已存在",
	}, nil
}
